<!--
 * @Description: 选择懒加载树
-->
<template>
  <div class="cpt_grey_disabled" v-if="disabled">{{
    Array.isArray(value)
      ? value
          .map(i => {
            return i[prop['label']]
          })
          .join('，')
      : value[label_p]
  }}</div>
  <el-select
    v-else
    :ref="select"
    class="_ehl_select_tree"
    popper-class="cpt_select_tree_pop"
    :value="labels"
    @visible-change="visibleChange"
  >
    <el-option :label="labels" :value="labels">
      <ehl-form
        v-if="formShow"
        :ref="select_tree"
        :options="formConfig"
        :data="formData"
        custom-class="select_tree"
      />
    </el-option>
  </el-select>
</template>
<script>
  import Vue from 'vue'
  import ehlForm from '@/common'
  import { Select, Option } from 'element-ui'
  Vue.use(Select)
  Vue.use(Option)
  export default {
    props: {
      devide: { type: String, default: () => ',' },
      loadNode: { type: Function, default: data => {} },
      value: { type: Array, required: true, default: () => [] },
      //是否不可编辑
      disabled: { type: Boolean, default: () => false },
      prop: {
        type: Object,
        default: () => ({
          label: 'label',
          children: 'children',
          disabled: 'disabled',
          isLeaf: 'leaf',
        }),
      },
    },
    components: { ehlForm },
    data() {
      return {
        select: `select_tree_ref_${Math.random()}`,
        select_tree: `select_tree_ref_${Math.random()}`,
        formShow: false,
        formData: { tree: this.value },
        formConfig: {
          tree: {
            type: 'tree',
            options: [{}],
            vertical: true,
            showAll: false,
            lazy: true,
            inputShow: false,
            checkbox: false,
            defaultExpandAll: false,
            lineStyle: { width: '100%' },
            style: { width: '100%' },
            prop: this.prop,
            loadNode: this.loadNode,
            nodeClick: function (data) {
              data.other.vue.selectBlur()
              data.other.vue.$emit('input', [data.current.node])
              data.other.vue.$emit('change', data.current.node, data)
            },
          },
        },
      }
    },
    computed: {
      labels() {
        let that = this
        return (
          this.formData.tree
            .map(i => {
              return i[that.prop['label']]
            })
            .join(this.devide) || ''
        )
      },
    },
    methods: {
      selectBlur() {
        this.$refs[this.select].blur()
      },
      visibleChange(val) {
        this.formShow = val
        if (val) {
          this.$nextTick(i => {
            this.$refs[this.select_tree].addParam({ vue: this })
          })
        }
      },
    },
  }
</script>
